package com.dh.service.impl;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.dh.core.common.enums.BizExceptionEnum;
import com.dh.core.common.exception.BussinessException;
import com.dh.dao.PermissionDao;
import com.dh.dao.RolePermissionDao;
import com.dh.dto.PermissionDTO;
import com.dh.entity.Permission;
import com.dh.service.PermissionService;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年12月6日 上午9:36:31
 * @Description 类说明 :
 */
@Service
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionDao permissionDao;
	
	@Autowired
	private RolePermissionDao rolePermissionDao;

	@Override
	public Page<Permission> findPermissionList(String option, Integer page, Integer pagesize, String sort,
			String order) {
		Permission permission = new Permission();
		Example<Permission> example = Example.of(permission);
		if (StringUtils.isNotBlank(option)) {
			permission.setName(option);
		}
		PageRequest pageable = null;
		if (StringUtils.isNotBlank(sort)) {
			Direction direction = Direction.ASC.toString().equals(order) ? Direction.ASC : Direction.DESC;
			Sort Sort = new Sort(direction, sort);
			pageable = PageRequest.of(page, pagesize, Sort);
		} else {
			pageable = PageRequest.of(page, pagesize);
		}
		return permissionDao.findAll(example, pageable);
	}

	@Override
	public Permission addPermission(PermissionDTO permissionDTO) {
		Permission permission = new Permission(UUID.randomUUID().toString(), permissionDTO.getName(), permissionDTO.getUrl());
		return permissionDao.save(permission);
	}

	@Override
	public Permission updatePermission(PermissionDTO permissionDTO) {
		try {
			Permission permission = permissionDao.findById(permissionDTO.getPid()).get();
			if(StringUtils.isNotBlank(permissionDTO.getName())) {
				permission.setName(permissionDTO.getName());
			}
			if(StringUtils.isNotBlank(permissionDTO.getUrl())) {
				permission.setUrl(permissionDTO.getUrl());
			}
			return permissionDao.save(permission);
		} catch (Exception e) {
			throw new BussinessException(BizExceptionEnum.NOT_PERMISSION);
		}
	}

	@Override
	public List<Permission> findAllPermissionList() {
		return permissionDao.findAll();
	}

	@Override
	public void removePermission(String pid) {
		rolePermissionDao.deleteByPid(pid);
		permissionDao.deleteById(pid);		
	}

}
